package com.example.order.service.impl;

import com.example.order.Order;
import com.example.order.feign.ProductFeignClient;
import com.example.order.service.OrderService;
import com.example.product.Product;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;



@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @Resource
    private ProductFeignClient productFeignClient;

    @Override
    public Order createOrder(Long productId, Long userId) {

        //Product product = getProductFromRemoteWithLoadBalanceV2(productId);
        log.info("准备获取商品{}信息", productId);
        Product product = productFeignClient.getProductById(productId);
        log.info("商品信息： {}", product);
        // 商品单价 * 商品数量 = 商品总金额
        BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(product.getNum()));

        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("北京");
        order.setProductList(List.of(product));
        order.setTotalAmount(totalAmount);
        return order;
    }

    private Product getProductFromRemoteWithLoadBalanceV2(Long productId) {
        String url = "http://service-product/product/" + productId;
        log.info("调用请求商品url： {}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    private Product getProductFromRemoteWithLoadBalance(Long productId) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("调用请求商品url： {}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


    private Product getProductFromRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("调用请求商品url： {}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
